# -*- coding: utf-8-*-
from openerp.osv import osv, fields, orm
SUPERUSER_ID = 1
import StringIO, xlwt, base64
from datetime import date
from xlrd.xldate import xldate_as_datetime
import time
#IHS6K 加班调休表增加新的类型“年假”，年假可以被调休核销
class import_annual_leave_wizard(osv.osv_memory):

    _name = 'import.annual.leave.wizard'
    _inherit = ['import.wizard']

    def need_column_date_header(self, cr, uid, context=None):
        vals = [('employee_id', u"员工姓名"), ('age', u"年份"), ('hour_qty', u"年假小时数"), ('expire_date', u"到期年月日(2018/03/08)")]
        return vals

    def return_vals_action(self, cr, uid, ids, this_id, context=None):
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'import.annual.leave.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': this_id,
            'views': [(False, 'form')],
            'target': 'new',
        }

    def judge_and_write_vals(self, cr, uid, ids, data_dcit, context=None):
        employee_obj = self.pool.get('hr.employee')
        employee_ids = employee_obj.search(cr, uid, [('name', '=', data_dcit.get('employee_id'))], context=context)
        if len(employee_ids) == 0:
            raise osv.except_osv(u'错误', u'员工%s不存在！'% data_dcit.get('employee_id'))
        elif len(employee_ids) > 1:
            raise osv.except_osv(u'错误', u'此员工%s,在系统中对应多个！' % data_dcit.get('employee_id'))
        employee_row = employee_obj.browse(cr, uid, employee_ids, context=context)
        start_date_time = '%s-01-01 00:00:00' % int(float(data_dcit.get('age')))
        end_date_time = '%s-12-31 16:00:00' % int(float(data_dcit.get('age')))
        expire_date = xldate_as_datetime(data_dcit.get('expire_date'), 0).strftime("%Y-%m-%d %H:%M:%S")
        data_dcit.update({'employee_id': employee_ids[0], 'type': 'annual_leave', 'is_approve': True,
                          'approver_user_id': uid, 'user_id': employee_row.user_id.id, 'approve_time':  fields.datetime.now(),
                          'note': u'人事统一导入年假', 'start_time': start_date_time, 'expire_date': expire_date,
                          'end_time': end_date_time})
        work_obj = self.pool.get('work.overtime.leave')
        work_id = work_obj.search(cr, uid, [('age', '=', int(data_dcit.get('age'))),
                                  ('employee_id', '=',  data_dcit.get('employee_id'))], context=context)
        if work_id:
            reconcile_ids = self.pool.get('work.time.reconcile').search(cr, uid, [('ol_id', '=', work_id),
                                                                  ('reconcile_id', '!=', False)], context=context)
            if reconcile_ids:
                raise osv.except_osv(u'错误', u'员工%s 年假以被占用不能修改！' % data_dcit.get('employee_id'))
            work_obj.write(cr, uid, work_id, data_dcit, context=context)
        else:
            work_obj.create(cr, uid, data_dcit, context=context)
        return True
        # 导出excel模版

    def export_template_xls(self, cr, uid, ids, context=None):
        xls = StringIO.StringIO()
        xls_workbook = xlwt.Workbook(encoding="utf8")
        data_sheet = xls_workbook.add_sheet('data')
        fileds_dict = self.need_column_date_header(cr, uid, context=context)
        for index, (filed_name, fields_string) in enumerate(fileds_dict):
            data_sheet.write(0, index, fields_string)
        xls_workbook.save(xls)
        xls.seek(0)
        out = base64.encodestring(xls.getvalue())
        self.write(cr, uid, ids, {'template_data': out, 'template_file_name': u'模版.xls'}, context=context)
        return {
            'type': 'ir.actions.act_url',
            'url': '/web/binary/saveas?model=' + self._name + '&field=template_data&id=%s&filename_field=template_file_name' % (
            ids[0]),
            'target': 'self',
        }
